package com.example.okhttp;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Administrator on 2018/10/19.
 */

public class HttpUrlConnUtil {

    public static String getContent(String urlStr){

        StringBuilder stringBuilder = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            int code = httpURLConnection.getResponseCode();
            String message=httpURLConnection.getResponseMessage();
            Log.e("androidLog","code="+code);
            Log.e("androidLog","message="+message);
            if(HttpURLConnection.HTTP_OK==code){
                InputStream is=httpURLConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is,"gbk"));
                String line;
                while((line=br.readLine())!=null){
                    stringBuilder.append(line);
                }
            }else if(HttpURLConnection.HTTP_MOVED_TEMP==code){
                String location = httpURLConnection.getHeaderField("Location");
                getContent(location);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("androidLog","res="+stringBuilder.toString());
        return stringBuilder.toString();
    }
}
